package com.jie.server.core.handler;

import cn.hutool.core.text.StrBuilder;
import com.jie.common.exception.entity.JieException;
import com.jie.common.http.entity.request.HttpRequest;
import com.jie.common.http.entity.response.HttpResponse;
import com.jie.server.core.ServerApplication;
import com.jie.server.core.annotation.Mapping;

import java.lang.reflect.Method;

/**
 * @author XieZhiJie
 * @date 2022/04/23 15:27
 */
public class HttpRequestHandler {

    /**
     * 处理请求
     * @param httpRequest 请求
     * @return            返回响应
     * @throws Exception  Exception
     */
    public static HttpResponse handleRequest(HttpRequest httpRequest) throws Exception {
        // 1.获取对应的controller类对象以及其类信息
        String[] paths = httpRequest.getUrl().split("/");
        // /jie/chat/user/get/xx/xx
        int start = "".equals(paths[0]) ? 3 : 2;
        Object controller = ServerApplication.getApplicationContext().getBean(paths[start++]);
        Class<?> clazz = controller.getClass();

        // 2.从url中获取可能要执行的方法getXxXx
        StrBuilder sb = new StrBuilder();
        sb.append(paths[start++]);
        for (int i = start; i < paths.length; i++) {
            char[] chars = paths[i].toCharArray();
            chars[0] = 'a' <= chars[0] && chars[0] <= 'z' ? (char) (chars[0] - 32) : chars[0];
            sb.append(chars);
        }

        // 3.反射执行对应的方法
        Method method = clazz.getDeclaredMethod(sb.toString(), HttpRequest.class, HttpResponse.class);
        if (!method.isAnnotationPresent(Mapping.class)) {
            throw new JieException("该方法无法用于处理请求!");
        }
        return (HttpResponse) method.invoke(controller, httpRequest, new HttpResponse());
    }

}
